package com.util;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;

import javax.servlet.http.HttpServletRequest;

import com.entity.BrowsingHistroy;

import net.sf.json.JSONObject;

public class BrowseUtil {
	
	
	/*
	 * 获取浏览历史BrowsingHistroy对象
	 * 
	 * */
	public static BrowsingHistroy getbrowsingHistroy(HttpServletRequest request){
		BrowsingHistroy browsingHistroy = new BrowsingHistroy();
		String ip = BrowseUtil.getIpAddr(request);
		//获取的是相对路径
		//String url1 = request.getRequestURI();   
		//获取的是完整路径
		StringBuffer url = request.getRequestURL(); 
		System.out.println("访问的接口路径为："+url);
		//获取访问者的物理地址
		browsingHistroy = BrowseUtil.getIpJudge(ip);
		browsingHistroy.setVisitIpAdd(browsingHistroy.getVisitIpAdd()+"-访问的接口方法名为："+url);
		return browsingHistroy;
	}
	
	/**
	 * 获取访问者的ip地址
	 * 
	 * */
	public static String getIpAddr(HttpServletRequest request) {  
	    String ip = request.getHeader("x-forwarded-for");  
	    if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {  
	        ip = request.getHeader("Proxy-Client-IP");  
	    }  
	    if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {  
	        ip = request.getHeader("WL-Proxy-Client-IP");  
	    }  
	    if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {  
	        ip = request.getRemoteAddr();  
	    }  
	    System.out.println("访问者的ip:"+ip);
	    return ip;  
	} 
	
	/**
	 * 根据ip地址获取访问者的物理位置
	 * 
	 * */
	public static BrowsingHistroy getAddressByIP(String strIP){ 
		BrowsingHistroy browsingHistroy = new BrowsingHistroy();
		try{
	    //qq查询地址
	    //URL url = new URL( "http://ip.qq.com/cgi-bin/searchip?searchip1=" + strIP); 
		//新浪地址
		//URL url = new URL("http://int.dpool.sina.com.cn/iplookup/iplookup.php?format=json&ip=" + strIP);
		//淘宝地址
		URL url = new URL("http://ip.taobao.com/service/getIpInfo.php?ip=" + strIP);
	    //延迟执行下面的代码
		//Thread.sleep(10000);
		URLConnection conn = url.openConnection(); 
	    BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8")); 
	    String line = null; 
	    StringBuffer result = new StringBuffer(); 
	    //while((line =  new String(reader.readLine().getBytes(),"UTF-8")) != null)
	    while((line = reader.readLine()) != null)
	    { 
	      System.out.println("line:================"+line);	
	      result.append(line); 
	    } 
	    reader.close(); 
	    String result1 = result.toString();
	    result1 = decode(result1);
	    System.out.println("result:"+result1);
	    JSONObject obj = JSONObject.fromObject(result1);
	    String country= JSONObject.fromObject(obj.optString("data")).optString("country");
	    String city= JSONObject.fromObject(obj.optString("data")).optString("city");
	    String isp= JSONObject.fromObject(obj.optString("data")).optString("isp");
	    String visitphyAdd = "获取成功,访问者所在国家为："+country+",访问者所在城市为："+city+",访问者ip类型为："+isp;
	    String visitIpAdd = "访问者ip为："+strIP;
	    System.out.println("获取成功,访问者所在国家为："+country+"\n访问者所在城市为："+city+"\n访问者ip类型为："+isp);
	    browsingHistroy.setVisitphyAdd(visitphyAdd);
	    browsingHistroy.setVisitIpAdd(visitIpAdd);
	    return browsingHistroy;
	  }catch( Exception e){ 
		System.out.println("获取失败");
		return browsingHistroy;
	  }
	}
	
	/**
	 * 处理uncode乱码
	 * 
	 * */
	public static String decode(String unicodeStr) {  
	    if (unicodeStr == null) {  
	        return null;  
	    }  
	    StringBuffer retBuf = new StringBuffer();  
	    int maxLoop = unicodeStr.length();  
	    for (int i = 0; i < maxLoop; i++) {  
	        if (unicodeStr.charAt(i) == '\\') {  
	            if ((i < maxLoop - 5)  
	                    && ((unicodeStr.charAt(i + 1) == 'u') || (unicodeStr  
	                            .charAt(i + 1) == 'U')))  
	                try {  
	                    retBuf.append((char) Integer.parseInt(  
	                            unicodeStr.substring(i + 2, i + 6), 16));  
	                    i += 5;  
	                } catch (NumberFormatException localNumberFormatException) {  
	                    retBuf.append(unicodeStr.charAt(i));  
	                }  
	            else  
	                retBuf.append(unicodeStr.charAt(i));  
	        } else {  
	            retBuf.append(unicodeStr.charAt(i));  
	        }  
	    }  
	    return retBuf.toString();  
	} 
	
	/**
	 * 通过IP地址来查询物理地址前的判断处理
	 * 
	 * */
	public static BrowsingHistroy getIpJudge(String ip) {  
		BrowsingHistroy browsingHistroy = new BrowsingHistroy();
		if(ip!=null && !"0:0:0:0:0:0:0:1".equals(ip)&& !"127.0.0.1".equals(ip)){
			browsingHistroy = BrowseUtil.getAddressByIP(ip);

		}else if("0:0:0:0:0:0:0:1".equals(ip)||"127.0.0.1".equals(ip)){
			browsingHistroy.setVisitIpAdd("访问地址为本地IP");
			browsingHistroy.setVisitphyAdd("访问的就是本地服务器地址");
		}
		else{
			browsingHistroy.setVisitIpAdd("未获取到IP");
			browsingHistroy.setVisitphyAdd("未获取到物理地址");
		}
	    return browsingHistroy;  
	} 
}
